# -*- coding: utf-8 -*-

import logging

from odoo import models, fields, api
from odoo.exceptions import UserError, ValidationError

_logger = logging.getLogger(__name__)


class OutgoingOrder(models.Model):
    _name = 'buliao.outgoing.order'

    name = fields.Char(u'单据号', required=True, index=True, readonly=True, default=lambda self: u'新建', copy=False)
    so_ids = fields.One2many('sale.order', 'outgoing_order_id', u'销售订单')
    partner_id = fields.Many2one(
        'res.partner', string=u'客户', readonly=True, required=True, index=True)
    state = fields.Selection([('draft', u'未付款'), ('partially', u'部分付款'), ('pay', u'已付款')], string=u'付款状态',
                             index=True, readonly=True, compute='_compute_state', default='draft')
    order_date = fields.Datetime(u'创建时间', readonly=True, state={'draft': [('readonly', False)]},
                                 default=fields.Datetime.now)

    @api.one
    @api.depends('so_ids', 'so_ids.invoice_status')
    def _compute_state(self):
        if all(so.invoice_state == 'invoiced' for so in self.so_ids):
            self.state = 'pay'
        elif any(so.invoice_state == 'invoiced' for so in self.so_ids):
            self.state = 'partially'
        else:
            self.state = 'draft'